package com.sixetc.sixcontroller.slice;

import ohos.rpc.*;

// 以连接提供加法计算能力的PA为例。为了提供跨设备连接能力，需要在本地发起连接侧和对端被连接侧分别实现代理
// 发起连接侧的代理示例如下：
public class MyRemoteProxy implements IRemoteBroker {
    private static final int ERR_OK = 0;
    private static final int COMMAND_PLUS = IRemoteObject.MIN_TRANSACTION_ID;
    private static final String DESCRIPTOR = "com.six.controller.DESCRIPTOR";
    private final IRemoteObject remote;

    public MyRemoteProxy(IRemoteObject remote) {
        this.remote = remote;
    }

    @Override
    public IRemoteObject asObject() {
        return remote;
    }

    public int plus(int a, int b) throws RemoteException {
        MessageParcel data = MessageParcel.obtain();
        MessageParcel reply = MessageParcel.obtain();
        // option不同的取值，决定采用同步或异步方式跨设备控制PA
        // 本例需要同步获取对端PA执行加法的结果，因此采用同步的方式，即MessageOption.TF_SYNC
        // 具体MessageOption的设置，可参考相关API文档
        MessageOption option = new MessageOption(MessageOption.TF_SYNC);
        data.writeInterfaceToken(DESCRIPTOR);
        data.writeInt(a);
        data.writeInt(b);

        try {
            remote.sendRequest(COMMAND_PLUS, data, reply, option);
            int errCode = reply.readInt();
            if (errCode != ERR_OK) {
                throw new RemoteException();
            }
            int result = reply.readInt();
            return result;
        } finally {
            data.reclaim();
            reply.reclaim();
        }
    }
}
